import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:viser_remit/core/helper/string_format_helper.dart';
import 'package:viser_remit/core/route/route.dart';
import 'package:viser_remit/core/utils/my_strings.dart';
import 'package:viser_remit/data/controller/home/home_controller.dart';
import 'package:viser_remit/data/model/send_money/send_money_model.dart';
import 'package:viser_remit/data/model/send_money/send_money_save_response_model.dart';
import 'package:viser_remit/data/repo/send_money/send_money_repo.dart';

import '../../../view/components/snack_bar/show_custom_snackbar.dart';
import '../../model/global/response_model/response_model.dart';
import '../../model/send_money_save/send_money_save_model.dart';

class SendMoneyController extends GetxController {
  SendMoneyRepo sendMoneyRepo;
  SendMoneyController({required this.sendMoneyRepo});

  TabController? tabController;

  HomeController homeController = Get.find();

  final FocusNode emailFocusNode = FocusNode();
  final FocusNode informationFocusNode = FocusNode();
  final FocusNode phoneNumberFocusNode = FocusNode();
  final FocusNode addressFocusNode = FocusNode();

  final TextEditingController emailController = TextEditingController();
  final TextEditingController recipientController = TextEditingController(text: "");
  final TextEditingController phoneNumberController = TextEditingController(text: "");
  final TextEditingController tempPhoneNumberController = TextEditingController(text: "");
  final TextEditingController addressController = TextEditingController(text: "");

  String saveRecipientStatus = 'off';

  String selectedDeliveryMethod = "Select One";

  bool saveRecipientValue = false;
  updateRecipient() {
    saveRecipientValue = !saveRecipientValue;
    if (saveRecipientValue == true) {
      saveRecipientStatus = 'on';
    } else {
      saveRecipientStatus = 'off';
    }
    update();
  }

  String todaySendMoney = "0.00";
  String thisMonthSendMoney = "0.00";

  String getDailyLimit() {
    var gsData = sendMoneyRepo.apiClient.getGSData().data?.generalSetting;
    var homeController = Get.find<HomeController>();

    double dailyLimit = double.parse(gsData?.userDailySendMoneyLimit.toString() ?? '0.00');
    double senderCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double limitBasedOnCurrency = dailyLimit * senderCurrencyRate;

    return Converter.formatNumber(limitBasedOnCurrency.toString());
  }

  String getMonthlyLimit() {
    var gsData = sendMoneyRepo.apiClient.getGSData().data?.generalSetting;
    var homeController = Get.find<HomeController>();

    double monthlyLimit = double.parse(gsData?.userMonthlySendMoneyLimit.toString() ?? '0.00');
    double senderCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double limitBasedOnCurrency = monthlyLimit * senderCurrencyRate;

    return Converter.formatNumber(limitBasedOnCurrency.toString());
  }

  // bool limitOver() {
  //   String limit = getPerTransfer();
  //   String sendMonyText = homeController.sendingAmountController.text.isEmpty ? "00" : homeController.sendingAmountController.text;

  //   if (double.parse(limit) < double.parse(sendMonyText)) {
  //     return true;
  //   }
  //   return false;
  // }
  bool limitOver() {
    String limit = getPerTransfer().replaceAll(' ', ''); // Remove spaces from limit
    String sendMoneyText = homeController.sendingAmountController.text.replaceAll(' ', ''); // Remove spaces from sendMoneyText

    // Check if sendMoneyText is empty
    if (sendMoneyText.isEmpty) {
      homeController.sendingAmountController.text == '0.0';
      return false;
    }

    // Allow only decimal numbers in limit and sendMoneyText
    RegExp decimalRegExp = RegExp(r'^\d*\.?\d*$');

    if (!decimalRegExp.hasMatch(limit) || !decimalRegExp.hasMatch(sendMoneyText)) {
      return true; // If limit or sendMoneyText contains invalid characters, return true
    }

    if (double.parse(limit) < double.parse(sendMoneyText)) {
      return true; // If limit is less than sendMoneyText, return true
    }

    return false; // Otherwise, return false
  }

  String getPerTransfer() {
    var gsData = sendMoneyRepo.apiClient.getGSData().data?.generalSetting;
    var homeController = Get.find<HomeController>();

    double sendMoneyLimit = double.parse(gsData?.userSendMoneyLimit.toString() ?? '0.0');
    double senderCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double perTransferBasedOnCurrency = sendMoneyLimit * senderCurrencyRate;

    return Converter.formatNumber(perTransferBasedOnCurrency.toString());
  }

  String getAvailableForTodayAmount() {
    var homeController = Get.find<HomeController>();

    double senderCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double todayMoneySend = double.parse(todaySendMoney) * senderCurrencyRate;
    double availableForToday = double.parse(getDailyLimit()) - todayMoneySend;

    return Converter.formatNumber(availableForToday.toString());
  }

  String getAvailableForThisMonthAmount() {
    var homeController = Get.find<HomeController>();

    double senderCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double todayMoneySend = double.parse(thisMonthSendMoney) * senderCurrencyRate;
    double availableForThisMonth = double.parse(getMonthlyLimit()) - todayMoneySend;

    return Converter.formatNumber(availableForThisMonth.toString());
  }

  bool isLoading = false;

  List<Sources> sourceOfFundsList = [];
  List<Purposes> purposeList = [];
  List<Recipients> recipientsList = [];

  Sources defaultSources = Sources(id: -1, name: MyStrings.selectOne);
  Purposes defaultPurpose = Purposes(id: -1, name: MyStrings.selectOne);
  Recipients defaultRecipients = Recipients(id: -1, name: MyStrings.selectOne);

  late Sources selectedSourceOfFunds = defaultSources;
  late Purposes selectedPurpose = defaultPurpose;
  late Recipients selectedRecipients = defaultRecipients;

  String selectedPaymentType = '1';

  setSelectedSourceOfFunds(Sources value) {
    selectedSourceOfFunds = value;
    update();
  }

  setSelectedPurpose(Purposes value) {
    selectedPurpose = value;
    update();
  }

  bool isPhoneNumberChanged = false;
  setSelectedPaymentType(String value) {
    selectedPaymentType = value;
  }

  setSelectedRecipients(Recipients value) {
    selectedRecipients = value;

    if (value.name == 'Select One') {
      recipientController.clear();
      emailController.clear();
      addressController.clear();
      phoneNumberController.clear();
    } else {
      recipientController.text = value.name.toString();
      emailController.text = value.email.toString();
      addressController.text = value.address.toString();
      phoneNumberController.text = value.mobile.toString();
      tempPhoneNumberController.text = value.mobile.toString();
    }
    update();
  }

  detectPhoneNumberChange(value) {
    if (value.toString() != tempPhoneNumberController.text) {
      isPhoneNumberChanged = true;
    } else {
      isPhoneNumberChanged = false;
    }
    update();
  }

  Future<void> loadSendMoneyData() async {
    isLoading = true;
    update();

    ResponseModel model = await sendMoneyRepo.getSendMoneyData();

    sourceOfFundsList.clear();
    purposeList.clear();
    recipientsList.clear();

    sourceOfFundsList.add(defaultSources);
    selectedSourceOfFunds = sourceOfFundsList[0];

    purposeList.add(defaultPurpose);
    selectedPurpose = purposeList[0];

    recipientsList.add(defaultRecipients);
    selectedRecipients = recipientsList[0];

    if (model.statusCode == 200) {
      SendMoneyModel sendMoneyModel = SendMoneyModel.fromJson(jsonDecode(model.responseJson));

      todaySendMoney = sendMoneyModel.data?.todaySendMoney.toString() ?? '0.00';
      thisMonthSendMoney = sendMoneyModel.data?.thisMonthSendMoney.toString() ?? '0.00';

      if (sendMoneyModel.data?.sources != null && sendMoneyModel.data!.sources!.isNotEmpty) {
        sourceOfFundsList.addAll(sendMoneyModel.data!.sources!);
      }

      if (sendMoneyModel.data?.purposes != null && sendMoneyModel.data!.purposes!.isNotEmpty) {
        purposeList.addAll(sendMoneyModel.data!.purposes!);
      }

      if (sendMoneyModel.data?.recipients != null && sendMoneyModel.data!.recipients!.isNotEmpty) {
        recipientsList.addAll(sendMoneyModel.data!.recipients!);
      }
    } else {
      CustomSnackBar.error(errorList: [model.message]);
    }

    isLoading = false;
    update();
  }

  String getCurrency() {
    String sendingCurrency = homeController.selectedSendCountry.currency.toString();
    return sendingCurrency;
  }

  String getSendingAmount() {
    String amount = homeController.sendingAmountController.text.toString();
    return amount;
  }

  String getCharge() {
    String charge = homeController.selectedDeliveryMethod.charge.toString();
    if (charge == 'null') {
      charge = '0.00';
      return charge;
    } else {
      return Converter.formatNumber(homeController.selectedDeliveryMethod.charge!.fixedCharge.toString());
    }
  }

  String getFinalAmount() {
    String amount = homeController.countPayableAmount();
    return amount;
  }

  String getAmountInUsd() {
    double finalAmount = double.parse(homeController.countPayableAmount());
    double sendingCurrencyRate = double.parse(homeController.selectedSendCountry.rate.toString());
    double calculateInUsd = finalAmount / sendingCurrencyRate;

    return Converter.formatNumber(calculateInUsd.toString());
  }

  bool submitLoading = false;

  String trxNumber = '';

  setTrxNumber(String value) {
    trxNumber = value;
  }

  saveSendMoneyData() async {
    submitLoading = true;

    update();

    SendMoneySaveModel model = getSendMoneySaveData();

    try {
      SendMoneySaveResponseModel responseModel = await sendMoneyRepo.saveSendMoneyDataToServer(model, homeController.serviceDynamicFormList);

      if (responseModel.status?.toLowerCase() == MyStrings.success.toLowerCase()) {
        setTrxNumber(responseModel.data?.sendMoney?.trx.toString() ?? '');

        if (responseModel.data?.paymentType.toString() == MyStrings.refundPayment) {
          CustomSnackBar.success(successList: [MyStrings.success]);

          Get.offAllNamed(
            RouteHelper.bottomNavBar,
          );
        } else if (responseModel.data?.paymentType.toString() == MyStrings.directPayment_) {
          Get.toNamed(RouteHelper.newDepositScreenScreen, arguments: [getFinalAmount(), getAmountInUsd(), responseModel.data!.sendMoney!.baseCurrencyRate]);
        }
      } else {
        CustomSnackBar.error(errorList: responseModel.message?.error ?? [MyStrings.somethingWentWrong]);
      }
    } catch (e) {
      if (kDebugMode) {
        print(e.toString());
      }
    }

    submitLoading = false;
    update();
  }

  getSendMoneySaveData() {
    SendMoneySaveModel model = SendMoneySaveModel(
      sendingAmount: getSendingAmount(),
      sendingCountry: homeController.selectedSendCountry.id.toString(),
      recipientAmount: homeController.receivingAmountController.text,
      recipientCountry: homeController.selectedReceiveCountry.id.toString(),
      sourceOfFunds: selectedSourceOfFunds.id.toString(),
      sendingPurpose: selectedPurpose.id.toString(),
      paymentType: selectedPaymentType,
      recipientName: recipientController.text.toString(),
      recipientMobile: phoneNumberController.text.toString(),
      recipientEmail: emailController.text.toString(),
      recipientAddress: addressController.text.toString(),
      deliveryMethod: homeController.selectedDeliveryMethodId,
      service: homeController.selectedServices.id.toString(),
      saveRecipient: saveRecipientStatus, //todo
    );

    return model;
  }

  goToRecipientScreen() {
    var homeController = Get.find<HomeController>();

    if (homeController.getSendingAmountDataValidation() == '') {
      if (limitOver()) {
        CustomSnackBar.error(errorList: [MyStrings.limitMSg]);
      } else {
        if (selectedSourceOfFunds.id == -1) {
          CustomSnackBar.error(errorList: [MyStrings.selectSourceOfFund]);
        } else if (selectedPurpose.id == -1) {
          CustomSnackBar.error(errorList: [MyStrings.selectSendingPurpose]);
        } else if (homeController.selectedSendCountry.id == -1) {
          CustomSnackBar.error(errorList: [MyStrings.selectSendingCountry]);
        } else if (homeController.selectedReceiveCountry.id == -1) {
          CustomSnackBar.error(errorList: [MyStrings.selectRecivingCountry]);
        } else if (homeController.sendingAmountController.text.isEmpty) {
          CustomSnackBar.error(errorList: [MyStrings.enterValidAmount]);
        } else {
          Get.toNamed(RouteHelper.recipientScreen);
        }
      }
    } else {
      CustomSnackBar.error(errorList: [homeController.getSendingAmountDataValidation()]);
    }
  }

  gotToNextPage() async {
    if (selectedSourceOfFunds.id != -1 && selectedPurpose.id != -1) {
      await saveSendMoneyData();
    } else {
      CustomSnackBar.error(errorList: [MyStrings.enterYourDetails]);
    }
  }
}
